#include "user/user.h"
#include "kernel/types.h"
#include "kernel/stat.h"

#define WR 1
#define RD 0

void dfs(int lpipe[2]){
    int first;
    close(lpipe[WR]);
    if(read(lpipe[RD], &first,sizeof(int)) != sizeof(int)){
        exit(0);
    }else{
        printf("prime %d\n", first);
        int rpipe[2];
        pipe(rpipe);
        if(fork() == 0){
            // child process
            dfs(rpipe);
        }
        else{
            // parent process
            int data;
            while(read(lpipe[RD],&data, sizeof(int)) == sizeof(int)){
                if(data % first){
                    write(rpipe[WR], &data, sizeof(int));
                }
            }
            close(lpipe[RD]);
            close(rpipe[WR]);
            close(rpipe[RD]);
            exit(0);

        }
    }

}



int main(int argc, char* argv){
    int lpipe[2];
    pipe(lpipe);
    for(int i=2; i<=35; i++){
        write(lpipe[WR], &i, sizeof(int));
    }
    
    if (fork() == 0){
        dfs(lpipe);
    }
    else{
        close(lpipe[WR]);
        close(lpipe[RD]);
        wait(0);
    }
    exit(0);
}